const fs = require('fs')
const co = require('co') // 异步流程控制co 模块;
const path = require('path')
const filePathRoot = path.resolve(__dirname, './dist')
const OSS = require('ali-oss')
const files = []
const uploadFlagList = []

const bucket = 'mm-imu' // oss的bucket空间名
const remotePath = '/' // 远程oss文件名(根据自己需要配置)

// 构建oss对象,这里可以找你们的后台或者运维人员开通上传oss的账号权限;
const client = new OSS({
  region: 'oss-cn-hangzhou',
  accessKeyId: 'LTAI4Fq1cNT1PmwuU67w2M3V',
  accessKeySecret: 'HH47nEHfPtM7vTTXBOTkZOLNVz33Hx',
  bucket
});

(() => {
  // 递归取出 打包后./dist 文件夹下所有文件的路径
  function readDirSync(filePath) {
    const filePaths = fs.readdirSync(filePath)
    filePaths.forEach((item) => {
      const cur_path = `${filePath}/${item}`
      const info = fs.statSync(cur_path)
      if (info.isDirectory()) {
        readDirSync(cur_path)
      } else {
        files.push(cur_path)
      }
    })
  }
  readDirSync(filePathRoot)

  co(function * () {
    try {
      for (let index = 0; index < files.length; index += 1) {
        const fileObj = files[index]
        // 提交文件到oss，这里要注意，阿里云不需要创建新文件夹，只要有路径，没有文件夹会自动创建
        const result = yield client.put(fileObj.replace(filePathRoot, remotePath), fileObj)
        uploadFlagList.push(result)
        if (!result) break
      }
      const uplaodFlag = uploadFlagList.find(item => item.res.statusCode != 200)
      if (uplaodFlag) {
        console.log('上传失败')
      } else {
        console.log('上传成功')
      }
    } catch (e) {
      console.log('上传失败,请查看日志: ', e)
    }
  })
})()
